package com.cn.why.springcloudskills.FaceTest;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * FOke join分而治之处理大批量任务
 */
public class FokeJoinTest extends RecursiveTask<Integer> {
    private int start = 0;
    private int end = 0;

    private FokeJoinTest(int start, int end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Integer compute() {

        if (end - start < 100) {
            // 当计算元素少于10的时候，那么这个任务足够小，不需要继续拆分
            int sum = 0;
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            int middle = (start + end) / 2;
            FokeJoinTest left = new FokeJoinTest(start, middle);
            FokeJoinTest right = new FokeJoinTest(middle + 1, end);
            left.fork();
            right.fork();
            return left.join() + right.join();
        }

    }



    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool pool = new ForkJoinPool();
        long startTime = System.currentTimeMillis();
        Future<Integer> value = pool.submit(new FokeJoinTest(0, 100000));
        long endTime = System.currentTimeMillis();

        // 打印结果 500500
        System.out.println("结果："+value.get()+"    时间："+(endTime-startTime)+"ms");
    }
}